package com.cpr.core.concurrency;

import lombok.SneakyThrows;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Chen Panrui
 * created at 2022/1/6 15:54
 * 文档: https://docs.oracle.com/javase/tutorial/essential/concurrency/join.html
 * The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,
 *
 * t.join();
 * causes the current thread to pause execution until t's thread terminates. Overloads of join allow the programmer to specify a waiting period.
 */
public class Joins {

    private final static int[] ARRAY = {1,2,3,4,5};

    public static void main(String[] args) throws InterruptedException {
        Interrupts.MyThread t1 = new Interrupts.MyThread();
        t1.setPrintCount(5);
        t1.start();

        // 让当前的main线程pause，t1线程执行完成之后，再执行main线程
        t1.join();

        for (int i = 0; i < 10; i++) {
            Thread.sleep(500);
            System.out.println("main线程:你好!i=" + i);
        }

        System.out.println("---实现2个线程交叉打印数字功能---");
        MyPrint runner = new MyPrint();
        Thread thread = new Thread(runner);
        thread.start();

        while (thread.isAlive()){
            // wait maximum of 1 second for print thread to finish.
            thread.join(1000);
            System.out.println("主线程: 等待子线程打印!");
        }
    }

    /**
     * 实现一个简单的 打印功能
     * 和 main线程组合在一起，实现交叉打印功能
     */
    private static class MyPrint implements Runnable{

        @SneakyThrows
        @Override
        public void run() {
            for (int i=0; i<ARRAY.length ; i++ ) {
                Thread.sleep(3000);
                System.out.format("子线程: 打印数组(%s,%s)\n", i, ARRAY[i]);
            }
            System.out.println("子线程: 结束了");
        }
    }
}
